<?php

namespace App\Http\Controllers;

use App\Services\UserService;
use App\User;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class UsersController extends BaseController
{
    protected $userService;

    public function __construct()
    {
        $this->userService = new UserService();
    }

    /**
     * 我的首页
     */
    public function getUser(){
        $this->uid = \session('uid');
//        用户信息：merchant_use_status商户状态：1-正常，5-禁用 商户状态如果禁用不允许切换至商家端，需提示
        $user = \DB::table('users')->where('id', $this->uid)->first();
//        已节省金额
        $user->saveAmount = \DB::table('users_orders')->where([
            ['uid', $this->uid],
            ['status', 50],
        ])->sum('real_return_money');

//        是否有过首次注册领取vip的记录
        $user->isReceiveVip = \DB::table('users_vip_receive_log')->where([
            ['type', 1],
            ['uid', $this->uid],
        ])->count();

//        本周有效订单数量
        $user->validOrderCount = \DB::table('users_orders')->where([
            ['uid', $this->uid],
        ])->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->where('status', 50)->count();

//        我的邀请已赚金额
        $user->myInviteAmount = \DB::table('users_balance_logs')->where([
            ['uid', $this->uid],
            ['type', 2],
            ['status', 1],
        ])->sum('money');

//        今日是否签到
        $user->isSign = \DB::table('users_sign')->where('uid', $this->uid)->where('date', date('Y-m-d'))->count();

        return returnJson(0, '', $user);
    }

    /**
     * 切换用户当前版本端状态
     */
    public function setUserCurrentType(){
        $this->uid = \session('uid');
        //用户当前版本端状态：0-用户端，1-商家端
        $type = intval(\request()->input('type'));
        \DB::table('users')->where('id', $this->uid)->update(['current_type'=>$type, 'updated_at'=>\getDt()]);
        return returnJson();
    }

    /**
     * 我的邀请
     */
    public function myInvite(){
        $this->uid = \session('uid');
        //我的邀请已赚金额
        $all = \DB::table('users_balance_logs')->where([
            ['uid', $this->uid],
            ['type', 2],
            ['status', 1],
        ])->sum('money');

//        昨日收益
        $tomorrow = \DB::table('users_balance_logs')->where([
            ['uid', $this->uid],
            ['type', 2],
            ['status', 1],
        ])->whereDate('created_at', date('Y-m-d', strtotime('-1 day')))->sum('money');

//        今日邀请人数
        $todayCount = \DB::table('users')->where('pid', $this->uid)->whereDate('created_at', date('Y-m-d'))->count();
//        累计邀请人数
        $total = \DB::table('users')->where('pid', $this->uid)->select(['avatar', 'name', 'id'])->get()->toArray();
        foreach ($total as &$item) {
            $item->orderCount = \DB::table('users_orders')->where([
                ['uid', $item->id],
            ])->whereIn('status', [40, 50])->count();
        }

        return returnJson(0, '', [
            'all' => $all,
            'tomorrow' => $tomorrow,
            'todayCount' => $todayCount,
            'total' => $total,
            'totalCount' => count($total),
        ]);
    }

    /**
     * 领取vip
     */
    public function receiveVip(){
        $this->uid = \session('uid');
        //        是否有过首次注册领取vip的记录
        $isReceiveVip = \DB::table('users_vip_receive_log')->where([
            ['type', 1],
            ['uid', $this->uid],
        ])->count();
        if( $isReceiveVip ){
            return returnJson(1, "您已领取过vip会员");
        }

        $re = $this->userService->receiveVip($this->uid);
        if( !$re ){
            return returnJson(1, "领取失败");
        }
        return returnJson();
    }

    /**
     * 订单满5领取vip
     */
    public function userFiveOrderLot(){
        $this->uid = \session('uid');
        $re = $this->userService->userFiveOrderLot($this->uid);
        if( !$re ){
            return returnJson(1, $this->userService->msg);
        }
        return returnJson();
    }

    /**
     * 天天领钱
     */
    public function everyDayReceive(){
        $this->uid = \session('uid');
        $data = [];
        //原余额
        $data['oldBalance'] = \DB::table('users')->where('id', $this->uid)->value('balance');
//        平均为用户省多少钱
        $saveAmountList = \DB::table('users_orders')
            ->whereBetween('created_at', [date('Y-m-d', strtotime('-7 day', time())), date('Y-m-d')])
            ->pluck('real_return_money');
        $data['saveAmount'] = collect($saveAmountList)->avg() * 30;

//        未领取的邀请的返现金
        $data['inviteAmount'] = \DB::table('users_balance_logs')
            ->where('uid', $this->uid)->where('type', 2)->where('status', 0)->sum('money');

//        是否签到
        $count  = \DB::table('users_sign')->where('uid', $this->uid)->where('date', date('Y-m-d'))->value('count');
        $data['isSign'] = $count?1:0;
//        持续签到天数
        $data['signData'] = ['code'=>1, 'msg'=>'已签到'];
        if( !$data['isSign'] ){
//            去签到
            $continuedNum = $this->userService->sign($this->uid);
            if ( $continuedNum ) $data['signData'] = ['code'=>0, 'msg'=>'签到成功'];
        }else{
            $continuedNum = $count;
        }

        $data['signList'] = \DB::table('users_sign')->where('uid', $this->uid)->limit($continuedNum)->orderBy('id', 'desc')->get();

//        中奖记录
        $data['lotList'] = \DB::table('users_sign as s')->join('users as u', 's.uid', '=', 'u.id')
            ->select(['s.*', 'u.name', 'u.avatar'])->whereIn('s.count', [3, 7])->limit(30)->orderBy('id', 'desc')->get()->toArray();
            foreach ($data['lotList'] as $key => &$value) {
                $value->name = mb_substr($value->name, 0, 1)."*";
                $value->lot_value = $value->lot_value . ($value->lot_type == 1 ? '乐淘币':'天VIP');
            }

//        免费领取
        $data['frees'] = \DB::table('frees')->get();
        foreach ($data['frees'] as $key => &$value) {
            $value->imgurl = 'uploads/'.$value->imgurl;
        }

        //        金
        $data['balance'] = \DB::table('users')->where('id', $this->uid)->value('balance');

        return returnJson(0, '', $data);
    }

    /**
     * 领取签到奖品
     */
    public function receiveLot(){
        $this->uid = \session('uid');
//        领奖id
        $id = request()->input('id');
        //原余额
        $oldBalance = \DB::table('users')->where('id', $this->uid)->value('balance');
        $re = $this->userService->receiveLot($this->uid, $id);
        if( $re ){
            //        金
            $balance = \DB::table('users')->where('id', $this->uid)->value('balance');
            return returnJson(0, $this->userService->msg, ['oldBalance'=>$oldBalance,'balance'=>$balance]);
        }

        return returnJson(1, $this->userService->msg);
    }

    /**
     * 领取好友返佣品鉴金
     */
    public function receiveInviteLot(){
        $this->uid = \session('uid');
        //原余额
        $oldBalance = \DB::table('users')->where('id', $this->uid)->value('balance');
        $re = $this->userService->receiveInviteLot($this->uid);
        if( $re ){
            //金
            $balance = \DB::table('users')->where('id', $this->uid)->value('balance');
            return returnJson(0, "领取成功", ['oldBalance'=>$oldBalance,'balance'=>$balance]);
        }

        return returnJson(1, $this->userService->msg);
    }

    /**
     * 饭点额度
     */
    public function mealAmount(){
        //        超过12点可以参加
        if( date('H') < 12 ){
            $meals = \DB::table('meals')->where('date', date('Y-m-d'))->first();
        }else{
            $meals = \DB::table('meals')->where('date', date('Y-m-d', strtotime('+1 day', time())))->first();
        }

        return returnJson(0, '', ['amount'=>$meals->base_amount+$meals->user_amount]);
    }

    /**
     * 参加饭点打卡
     */
    public function joinMeals(){
        $this->uid = \session('uid');
        $amount = \request()->input('amount');
        if( !$amount ){
            return returnJson(1, '参与品鉴金有误');
        }
//        超过12点可以参加
        if( date('H') < 12 ){
            return returnJson(1, '当前时间无法参与明日活动');
        }
//        参与打卡
        $re = $this->userService->joinMeals($this->uid, $amount);
        if( $re ){
            return returnJson();
        }

        return returnJson(1, $this->userService->msg);
    }

    /**
     * 打卡签到
     */
    public function signMeals(){
        $this->uid = \session('uid');
        //        11-12点可以参加
        if( date('H') != 11 ){
            return returnJson(1, '当前时间无法签到');
        }
//        签到打卡
        $re = $this->userService->signMeals($this->uid);
        if( $re ){
            return returnJson();
        }

        return returnJson(1, $this->userService->msg);
    }

    /**
     * 提现列表
     */
    public function withdrawalList(){
        $this->uid = \session('uid');
        $list = \DB::table('users_withdrawal')->where('uid', $this->uid)->orderBy('id', 'desc')->select(['money', 'status', 'transaction_no', 'created_at'])->get();
        return returnJson(0, '', $list);
    }

    /**
     * 添加formid
     *
     * @return void
     */
    public function addFormid(){
        $this->uid = \session('uid');
        $formid = request()->input('formid');
        if( !$formid ){
            return returnJson(1, '缺少参数');
        }
        DB::table('user_formids')->insert(['uid'=>$this->uid, 'formid'=>$formid, 'created_at'=>time()]);
        return returnJson(0);
    }

    /**
     * 修改用户电话
     */
    public function editUserPhone(Request $request){
        $phone = $request->input('phone');
        if(!$phone){
            return returnErrorJson('参数错误');
        }
        $this->uid = \session('uid');
        $res = User::where("id",$this->uid)->update(['phone'=>$phone]);
        if($res){
            return returnJson();
        }else{
            return returnErrorJson();
        }
    }
}
